package inutan.login.controller;

import inutan.common.constant.Constant;
import inutan.common.entity.GatewayServerInfo;
import inutan.common.message.ActionErrorEnum;
import inutan.common.utils.RSAUtils;
import inutan.login.entity.UserInfo;
import inutan.login.entity.ServerInfoVo;
import inutan.login.service.ServerInfoService;
import org.ricks.common.json.JSONArray;
import org.ricks.common.json.JSONObject;
import org.ricks.common.utils.TimeUtils;
import org.ricks.ioc.anno.Autowired;
import org.ricks.ioc.anno.Controller;
import org.ricks.ioc.anno.RequestMapping;
import org.ricks.net.anno.Param;
import org.ricks.net.http.HttpRequest;
import org.ricks.orm.OrmContext;
import java.util.List;
import java.util.Optional;

@Controller
public class CommonController {

    @Autowired
    private ServerInfoService serverInfoService;

    @RequestMapping("/loginValidate")
    public JSONObject loginValidate(@Param("userToken") long userToken, @Param("sign") String sign) {
        UserInfo userInfo = OrmContext.me().executeLoad(UserInfo.class, "select * from login_user_info where userToken = ? ", userToken);
        ActionErrorEnum.loginValidateNotData.assertNonNull(userInfo);
        loginValidateRSA(userInfo, sign);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msgCode", 0);
        jsonObject.put("message","登陆校验成功");
        jsonObject.put("userId", userInfo.getId());
        return jsonObject;
    }

    /**
     * 登录校验 RSA
     * @param userInfo
     */
    public void loginValidateRSA(UserInfo userInfo, String sign) {
        StringBuilder builder = new StringBuilder(userInfo.getUsername());
        builder.append("&");
        builder.append(userInfo.getUserToken());
        builder.append("&");
        builder.append(userInfo.getPublisher());
        builder.append("&");
        builder.append(userInfo.getLoginTime());
        try {
            System.err.println( sign.replaceAll(" ", "+"));
            String decryptedMsg = RSAUtils.decryptByPrivateKey(sign.replaceAll(" ", "+"), RSAUtils.getPrivateKey(Constant.PRIVATE_KEY));
            ActionErrorEnum.validateLogin.assertTrue(builder.toString().equals(decryptedMsg),"登录校验异常 ");
        } catch (Exception e) {
            ActionErrorEnum.validateLogin.assertTrue(false,"登录RSA校验异常 ");
        }
    }

    @RequestMapping("/gatewayHeartbeat")
    public void gatewayHeartbeat(HttpRequest request, @Param("gatewayInfo") JSONObject gatewayInfo) {
        int gatewayId = gatewayInfo.getInt("gatewayId");
        Optional<GatewayServerInfo> optionalGatewayServerInfo = Optional.ofNullable(OrmContext.me().load(GatewayServerInfo.class, gatewayId));
        optionalGatewayServerInfo.ifPresentOrElse(gatewayServerInfo -> {
            gatewayServerInfo.setFlushTime(TimeUtils.currentTimeMillis());
            OrmContext.me().update(gatewayServerInfo);
        }, () -> addGatewayInfo(gatewayInfo));
    }

    private void addGatewayInfo(JSONObject gatewayInfo){
        GatewayServerInfo gatewayServerInfo = new GatewayServerInfo();
        long gatewayId = gatewayInfo.getInt("gatewayId");
        gatewayServerInfo.setId(gatewayId);
        gatewayServerInfo.setInnerAddress(gatewayInfo.getString("localAddress"));
        gatewayServerInfo.setRemoteAddress(gatewayInfo.getString("remoteAddress"));
        gatewayServerInfo.setFlushTime(TimeUtils.currentTimeMillis());
        OrmContext.me().insert(gatewayServerInfo);
    }

    /**
     * @Explain --> 获得当前启动状态的业务服信息
     * @Author yanwang
     * @Date 2023/3/27 18:49
     **/
    @RequestMapping("/getAllServer")
    public Object getAllServer(){
        List<ServerInfoVo> infoList =serverInfoService.getAllServer();
        JSONArray jsonArray = new JSONArray(infoList);
        return jsonArray.toString();
    }
}
